package com.example.onlinemusic.controller;

import com.example.onlinemusic.common.Constant;
import com.example.onlinemusic.common.ResponseBodyMessage;
import com.example.onlinemusic.mapper.LoveMusicMapper;
import com.example.onlinemusic.model.Music;
import com.example.onlinemusic.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/lovemusic")
public class LoveMusicController {
    @Autowired
    private LoveMusicMapper loveMusicMapper;

    @RequestMapping("/favoritemusic")
    public ResponseBodyMessage<Boolean> favoriteMusic(@RequestParam String id, HttpServletRequest request){
        int musicId = Integer.parseInt(id);
        System.out.println("musicId:"+musicId);
        // 1. 检查是否登录
        HttpSession session = request.getSession(false);
        if(session == null || session.getAttribute(Constant.USER_SESSION_KEY) == null){
            System.out.println("没有登录！");
            return new ResponseBodyMessage<>(-1,"请登录后上传！",false);
        }

        User user = (User)session.getAttribute(Constant.USER_SESSION_KEY);
        int userId = user.getId();
        System.out.println("userId:"+userId);

        // 再收藏之前 查询数据库，看看之前是否收藏了
        Music music = loveMusicMapper.findLoveMusicByMusicIdAndUserId(userId,musicId);
        if(music != null){
            // 之前收藏过，就不能再进行收藏了，思考 取消收藏的功能
            return new  ResponseBodyMessage<>(-1,"您之前收藏过这个音乐",false);
        }

        boolean ret = loveMusicMapper.insertLoveMusic(userId,musicId);
        if(ret){
            return new  ResponseBodyMessage<>(1,"收藏成功！",true);
        }else {
            return new  ResponseBodyMessage<>(-1,"收藏失败！",false);
        }
    }

    @RequestMapping("/cancellovemusic")
    public ResponseBodyMessage<Boolean> cancelLoveMusic(@RequestParam String id, HttpServletRequest request){
        int musicId = Integer.parseInt(id);
        // 1. 检查是否登录
        HttpSession session = request.getSession(false);
        if(session == null || session.getAttribute(Constant.USER_SESSION_KEY) == null){
            System.out.println("没有登录！");
            return new ResponseBodyMessage<>(-1,"请登录后上传！",false);
        }
        User user = (User)session.getAttribute(Constant.USER_SESSION_KEY);
        int userId = user.getId();

        int ret = loveMusicMapper.cancelLoveMusic(userId,musicId);
        if (ret == 1){
            return new ResponseBodyMessage<>(0,"取消收藏成功！",true);
        }else{
            return new ResponseBodyMessage<>(0,"取消收藏失败！",true);
        }
    }


}
